package com.itheima.controller;

import com.itheima.abvice.LogOperation;
import com.itheima.anno.Log;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    // 查询所有部门,按照更新时间倒序排序
    @GetMapping
    public Result list() {
        log.info("查询所有部门信息");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    // 按照id删除部门
    @LogOperation
    @Log
    @DeleteMapping
    public Result delete(Integer id) {
        log.info("删除部门id为{}的部门",id);
        // state为0的时候不能删除,为1的时候可以删除
        boolean state = deptService.deleteById(id);
        if (!state) {
            log.info("id为{}的部门下面还有员工,删除失败", id);
            return Result.error("当前部门还有员工,不能删除");
        } else {
            return Result.success();
        }
    }

    // 添加部门
    @Log
    @PostMapping
    public Result add(@RequestBody Dept dept) {
        log.info("新增部门:{}", dept);
        deptService.save(dept);
        return Result.success();
    }

    // 根据id查询部门
    @GetMapping("/{deptId}")
    public Result getById(@PathVariable("deptId") Integer deptId) {
        log.info("查询id为{}的部门", deptId);
        Dept dept = deptService.getById(deptId);
        return Result.success(dept);
    }

    // 根据id修改部门
    @Log
    @PutMapping
    public Result update(@RequestBody Dept dept) {
        log.info("修改部门信息:{}", dept);
        deptService.update(dept);
        return Result.success();
    }
}
